<?php
/**
 * Created by PhpStorm.
 * User: yyc
 * Date: 2018/7/27
 * Time: 10:01
 */
class OAApplyController extends BaseController
{
    /**
     * @var object 验证方法对象
     */
    protected $validator;
    /**
     * @var array 返回数据模板
     */
    protected $response = ['code' => 0, 'msg' => 'ok'];
    /**
     * @var object 用户信息
     */
    protected $user;

    /**
     * 用于鉴定用户的token
     * OAApprovalModelController constructor.
     */
    public function __construct()
    {
        header('Access-Control-Allow-Origin:*');	//解决资源跨域问题
	header('Access-Control-Allow-Credentials', 'true');
        
        $this->user = $this->verificationOAUserToken(Input::get('token'), $this->response);
    }
    
    /**
     * 获取我的申请列表 && 已归档列表  搜索/列表/分页
     * User: yyc
     * Date: 2018/7/27
     * Time: 10:23
     * @param token    string  获取凭证
     * @param search   string  模糊查找条件（摘要）
     * @param page     integer 当前页码
     * @param pageSize integer 每页显示条数
     * @param status   array   审批状态 1:未提交;2:审批中;3:同意;4:不同意;5:已撤回;6:已删除
     * @param needPage   integer   是否否需要分页默认分页 （1不分页）
     * @param typeId   array   审批类型ID
     * @return string
     */
    public function activeApply()
    {
        $this->validator = Validator::make(Input::all(), [
            'token' => 'required',
            'page' => 'integer',
            'page_size' => 'integer',
            'status' => 'array',        //已归档必传
            'type' => 'array',
            'needPage' => 'integer',
        ]);

        do {
            //验证token
            if ($this->validator->fails()) {
                $this->response = Lang::get('oa_error.args_error_100000');
                $this->response += ['result' => $this->validator->messages()];
                break;
            }
            //验证用户
            if (!$this->user) {
                break;
            }

            $search     = Input::get('search', '');             //查询条件（摘要）
            $typeId     = Input::get('type', '');               //审批类型
            $status     = Input::get('status', '');             //审批状态
            $page       = Input::get('page', 1);                //页码 [默认 1]
            $pageSize   = Input::get('page_size', 10);           //每页显示数据条数 [默认 10]
            $needPage   = Input::get('needPage', '');           //是否需要分页（不需要 1）
            //获取我的申请
            $this->response = [
                'code' => 0,
                'msg' => 'ok',
                'result' => [
                    'type' => OAApprovalModel::typeNeedAll(),
                    'infoAll' => OAApply::activeApply($this->user->id, $needPage, $search, $page, $pageSize, $status, $typeId, 'NO'),
                ],
            ];
        } while (false);
        //返回数据
        Log::info('info', [
            'system' => 'oa',
            'event' => 'apply/activeApply',
            'input' => Input::all(),
            'output' => $this->response
        ]);

        return json_encode($this->response, JSON_UNESCAPED_UNICODE);

    }

    /**
     * 获取我的审批  搜索/列表/分页
     * User: yyc
     * Date: 2018/8/1
     * Time: 17:00
     * @param token    string  获取凭证
     * @param search   string  模糊查找条件（摘要）
     * @param page     integer 当前页码
     * @param pageSize integer 每页显示条数
     * @param status   int     审批状态 1:待处理;2:审批中;3:同意;4:不同意;5:已撤回;空的时候是全部
     * @param typeId   array   审批类型ID
     * @return string
     */
    public function  passiveApply()
    {
        $this->validator = Validator::make(Input::all(), [
            'token' => 'required',
            'page' => 'integer',
            'page_size' => 'integer',
            'status' => 'integer|between:0,5',
            'type' => 'array',
        ]);

        do {
            //验证token
            if ($this->validator->fails()) {
                $this->response = Lang::get('oa_error.args_error_100000');
                $this->response += ['result' => $this->validator->messages()];
                break;
            }
            //验证用户
            if (!$this->user) {
                break;
            }

            $search     = Input::get('search', '');             //查询条件（摘要）
            $typeId     = Input::get('type', '');               //审批类型
            $status     = Input::get('status', '');             //审批状态
            $page       = Input::get('page', 1);                //页码 [默认 1]
            $pageSize   = Input::get('page_size', 10);           //每页显示数据条数 [默认 10]

            //获取我的审批
            $this->response = [
                'code' => 0,
                'msg' => 'ok',
                'result' => [
                    'type' => OAApprovalModel::typeNeedAll(),
                    'info' => OAApply::passiveApply($this->user->id, $search, $page, $pageSize, $status, $typeId, 'NO'),
                ],
            ];
        } while (false);
        //返回数据
        Log::info('info', [
            'system' => 'oa',
            'event' => 'apply/passiveApply',
            'input' => Input::all(),
            'output' => $this->response
        ]);

        return json_encode($this->response);

    }

    /**
     * 获取抄送给我的审批  搜索/列表/分页
     * User: yyc
     * Date: 2018/8/1
     * Time: 17:30
     * @param token    string  获取凭证
     * @param search   string  模糊查找条件（摘要）
     * @param page     integer 当前页码
     * @param pageSize integer 每页显示条数
     * @param status   array   审批状态 1:未提交;2:审批中;3:同意;4:不同意;5:已撤回;6:已删除
     * @param typeId   array   审批类型ID
     * @return string
     */
    public function  copyApply()
    {
        $this->validator = Validator::make(Input::all(), [
            'token' => 'required',
            'page' => 'integer',
            'page_size' => 'integer',
            'status' => 'array',
            'type' => 'array',
        ]);

        do {
            //验证token
            if ($this->validator->fails()) {
                $this->response = Lang::get('oa_error.args_error_100000');
                $this->response += ['result' => $this->validator->messages()];
                break;
            }
            //验证用户
            if (!$this->user) {
                break;
            }

            $search     = Input::get('search', '');             //查询条件（摘要）
            $typeId     = Input::get('type', '');               //审批类型
            $status     = Input::get('status', '');             //审批状态
            $page       = Input::get('page', 1);                //页码 [默认 1]
            $pageSize   = Input::get('page_size', 10);           //每页显示数据条数 [默认 10]

            //获取抄送给我的审批
            $this->response = [
                'code' => 0,
                'msg' => 'ok',
                'result' => [
                    'type' => OAApprovalModel::typeNeedAll(),
                    'info' => OAApply::copyApply($this->user->id, $search, $page, $pageSize, $status, $typeId, 'NO'),
                ],
            ];
        } while (false);
        //返回数据
        Log::info('info', [
            'system' => 'oa',
            'event' => 'apply/copyApply',
            'input' => Input::all(),
            'output' => $this->response
        ]);

        return json_encode($this->response);

    }

    /**
     * 获取申请详情
     * User: yyc
     * Date: 2018/8/2
     * Time: 15:10
     * @param token     string  获取凭证
     * @param applyId   int     申请Id
     * @param type   int     是从哪一个入口进入
     * @return string
     */
    public function infoApply()
    {
        $this->validator = Validator::make(Input::all(), [
            'token' => 'required',
            'applyId' => 'required|integer',
            'type' => 'integer',
        ]);

        do {
            //验证token
            if ($this->validator->fails()) {
                $this->response = Lang::get('oa_error.args_error_100000');
                $this->response += ['result' => $this->validator->messages()];
                break;
            }
            //验证用户
            if (!$this->user) {
                break;
            }

            $applyId     = Input::get('applyId');            //申请ID
            $type        = Input::get('type');            //从哪个入口进入

            //获取申请详情
            $this->response = [
                'code' => 0,
                'msg' => 'ok',
                'result' => OAApply::infoApply($applyId, $this->user->id, $type),
            ];
        } while (false);
        //返回数据
        Log::info('info', [
            'system' => 'oa',
            'event' => 'apply/copyApply',
            'input' => Input::all(),
            'output' => $this->response
        ]);
        return json_encode($this->response);
    }

    /**
     * 开始审批
     * @param token             string      获取凭证
     * @param applyId           string      申请编号
     * @param flowType          integer     同意还是不同意  (1:同意;2:不同意;)
     * @param userIds           array       当前等级审批人的id
     * @param applyLevel        integer     审批等级
     * @param flowApprovalWay   integer     审批方式(1:单人审批;2:会签;3:或签;)
     * @param oType             string      审批意见
     * @return string
     */
    public function agreeOrNo()
    {
        $this->validator = Validator::make(Input::all(), [
            'token' => 'required',
            'applyId' => 'required|integer',
            'flowType' => 'integer|required|between:1,2',
            'userIds' => 'array|required',
            'applyLevel' => 'integer|required',
            'flowApprovalWay' => 'integer|required|between:1,3',
            'postil' => 'string',
        ]);

        do {
            //验证token
            if ($this->validator->fails()) {
                $this->response = Lang::get('oa_error.args_error_100000');
                $this->response += ['result' => $this->validator->messages()];
                break;
            }
            //验证用户
            if (!$this->user) {
                break;
            }

            $applyLevel  = Input::get('applyLevel');            //审批等级
            $userIds     = Input::get('userIds');               //当前等级审批人的id
            $flowType    = Input::get('flowType');              //同意还是不同意  (1:同意;2:不同意;)
            $opType     = Input::get('postil');               //申请编号
            $applyId     = Input::get('applyId');               //申请ID
            $flowApprovalWay = Input::get('flowApprovalWay');   //审批方式(1:单人审批;2:会签;3:或签;)
            $userID      = $this->user->id;

            $status = [
                1 => '同意第' . $applyLevel . '级审批',
                2 => '不同意' . $applyLevel . '级审批',
            ];

            if (!in_array($this->user->id, $userIds)) {
                $this->response = Lang::get('oa_error.apply_controller_status_error_212003');
                break;
            }

            $oldData = json_encode(OAApply::where('id', '=', $applyId)->first());
            $userIds = array_values(array_diff($userIds, [$userID])); //除当前审批人之外的其他审批人
            //开始审批
            try {
               $this->response = OAApply::agreeOrNo($applyId, $userIds, $flowApprovalWay, $applyLevel, $userID, $flowType, $opType);
            } catch (Exception $e) {
                break;
            }

            //写入系统日志
            $newData = json_encode(OAApply::where('id', '=', $applyId)->first());
            OAOpLog::writeLog('apply/agreeOrNo', 2, $status[$flowType], $oldData, $newData, $userID);

        } while (false);
        //返回数据
        Log::info('info', [
            'system' => 'oa',
            'event' => 'apply/agreeOrNo',
            'input' => Input::all(),
            'output' => $this->response
        ]);
        return json_encode($this->response);
    }

    /**
     * @param token             string      获取凭证
     * @return string
     * @author yyc
     * @date 2018/8/21 10:51
     */
    public function countAll()
    {
        $this->validator = Validator::make(Input::all(), [
            'token' => 'required',
        ]);

        do {
            //验证token
            if ($this->validator->fails()) {
                $this->response = Lang::get('oa_error.args_error_100000');
                $this->response += ['result' => $this->validator->messages()];
                break;
            }
            //验证用户
            if (!$this->user) {
                break;
            }

            $activeStatus  = Input::get('activeStatus', [2]);                //我的申请消息
            $passiveStatus = Input::get('passiveStatus', 1);                 //我的审批消息
            $copyStatus    = Input::get('copyStatus', [2]);                  //抄送给我消息

            $activeCount = OAApply::activeApply($this->user->id, '', '', 1, 10, $activeStatus, '', '');
            $passiveCount = OAApply::passiveApply($this->user->id, '', 1, 10, $passiveStatus, '', '');
            $copyCount = OAApply::copyApply($this->user->id, '', 1, 10, $copyStatus, '', '');

            $this->response = [
                'code' => 0,
                'msg' => 'ok',
                'result' => [
                    'activeCount' => empty($activeCount) ? '' : $activeCount,
                    'passiveCount' => empty($passiveCount) ? '' : $passiveCount,
                    'copyCount' => empty($copyCount) ? '' : $copyCount,
                ],
            ];

        } while (false);
        //返回数据
        Log::info('info', [
            'system' => 'oa',
            'event' => 'apply/countAll',
            'input' => Input::all(),
            'output' => $this->response
        ]);
        return json_encode($this->response);

    }

}